package ijij41.togetherTrain.personal;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

import ijij41.network.NetworkRequester;
import ijij41.togetherTrain.Constants;
import ijij41.togetherTrain.R;
import ijij41.togetherTrain.common.RoomViewActivity;
import ijij41.togetherTrain.config.TrainConfig;
import ijij41.togetherTrain.participate.RoomListActivity;

import ijij41.togetherTrain.recruit.RoomCreateActivity;
import ijij41.togetherTrain.recruit.TrainListRecruitActivity;
import ijij41.togetherTrain.resource.MyTicketRoomListRow;
import ijij41.togetherTrain.resource.RoomListRow;
import ijij41.togetherTrain.resource.TrainListRow;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

public class MyTicketListActivity extends Activity {

	private ArrayList<MyTicketRoomListRow> myCreateRoom;
	private ArrayList<MyTicketRoomListRow> myParticipateRoom;

	private TrainListAdapter myCreateRoomListAdapter;
	private TrainListAdapter myParticipateRoomListAdapter;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.my_ticket_list);

		initComponent();

	}

	private void initComponent() {

		myCreateRoom = new ArrayList<MyTicketRoomListRow>();
		myParticipateRoom = new ArrayList<MyTicketRoomListRow>();

		myCreateRoomListAdapter = new TrainListAdapter(this,
				R.layout.search_row, myCreateRoom);

		// TODO search_row don't care ??? because using inflate
		myParticipateRoomListAdapter = new TrainListAdapter(this,
				R.layout.search_row, myParticipateRoom);

		ArrayList<MyTicketRoomListRow> coll = NetworkRequester.getInstance()
				.getMyTickets(TrainConfig.user_id);

		Iterator<MyTicketRoomListRow> itr = coll.iterator();
		while (itr.hasNext()) {
			MyTicketRoomListRow ticketRoom = (MyTicketRoomListRow) itr.next();
			if (ticketRoom.getIsMaster()) {
				myCreateRoom.add(ticketRoom);
			} else {
				myParticipateRoom.add(ticketRoom);
			}
		}

		// create our list and custom adapter
		SeparatedListAdapter adapter = new SeparatedListAdapter(this);
		adapter.addSection("만든 방", myCreateRoomListAdapter);
		adapter.addSection("참여방", myParticipateRoomListAdapter);
		ListView list = (ListView) findViewById(R.id.room_list);
		list.setAdapter(adapter);
		list.setOnItemClickListener(mItemClickListener);

		// event handler
		findViewById(R.id.btn_back_img).setOnClickListener(mClickListener);
	}

	private AdapterView.OnItemClickListener mItemClickListener = new AdapterView.OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int position,
				long arg3) {

			MyTicketRoomListRow myTicketRoomListRow = (MyTicketRoomListRow) arg0
					.getAdapter().getItem(position);

			Intent roomViewIntent = new Intent(MyTicketListActivity.this,
					RoomViewActivity.class);

			roomViewIntent.putExtra("room_idx", myTicketRoomListRow.getIdx());

			startActivity(roomViewIntent);

		}

	};

	
	
	private Button.OnClickListener mClickListener = new Button.OnClickListener() {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {

			case R.id.btn_back_img:
				finish();
				break;

			default:
				break;
			}

		}
	};

	private class TrainListAdapter extends ArrayAdapter<MyTicketRoomListRow> {

		private ArrayList<MyTicketRoomListRow> items;

		public TrainListAdapter(Context context, int textViewResourceId,
				ArrayList<MyTicketRoomListRow> objects) {
			super(context, textViewResourceId, objects);

			items = objects;

		}

		public View getView(int position, View v, ViewGroup parent) {
			// layout에다가 데이터를 담아서 리턴시켜야 하는데, layout을 어떻게 초기화 시키는가?
			// Inflater는 지정한 layout의 객체들을 모두 생성하고 생성된 객체간의 계층구조까지 완성해주는 놈
			LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			v = vi.inflate(R.layout.my_ticket_list_row, null);

			// 보여주어야할 항목이 몇번째 항목이냐에 따라 그에 맞는 데이터 추츨
			MyTicketRoomListRow u = items.get(position);

			if (u != null) {
				TextView trainNumTv = (TextView) v.findViewById(R.id.train_num);
				TextView startStationTv = (TextView) v
						.findViewById(R.id.start_station);
				TextView startTimeTv = (TextView) v
						.findViewById(R.id.start_time);
				TextView endStationTv = (TextView) v
						.findViewById(R.id.end_station);
				TextView endTimeTv = (TextView) v.findViewById(R.id.end_time);

				TextView roomNumTv = (TextView) v
						.findViewById(R.id.room_num_value);

				TextView roomMasterTv = (TextView) v
						.findViewById(R.id.room_master_value);
				TextView roomMemberNumTv = (TextView) v
						.findViewById(R.id.room_member_num_value);

				trainNumTv.setText(u.getTrainNum());
				roomNumTv.setText(u.getRoom_num());
				roomMasterTv.setText(u.getMaster_id());
				roomMemberNumTv.setText(u.getCurrentNumMember() + "/"
						+ u.getMaxNumMember());
				startStationTv.setText(u.getStartStation());
				startTimeTv.setText(u.getStartTime());
				endStationTv.setText(u.getEndStation());
				endTimeTv.setText(u.getEndTime());

			}
			return v;
		}
	}

	private class SeparatedListAdapter extends BaseAdapter {

		public final Map<String, Adapter> sections = new LinkedHashMap<String, Adapter>();
		public final ArrayAdapter<String> headers;
		public final static int TYPE_SECTION_HEADER = 0;

		public SeparatedListAdapter(Context context) {
			headers = new ArrayAdapter<String>(context, R.layout.list_header);
		}

		public void addSection(String section, Adapter adapter) {
			this.headers.add(section);
			this.sections.put(section, adapter);
		}

		public Object getItem(int position) {
			for (Object section : this.sections.keySet()) {
				Adapter adapter = sections.get(section);
				int size = adapter.getCount() + 1;

				// check if position inside this section
				if (position == 0)
					return section;
				if (position < size)
					return adapter.getItem(position - 1);

				// otherwise jump into next section
				position -= size;
			}
			return null;
		}

		public int getCount() {
			// total together all sections, plus one for each section header
			int total = 0;
			for (Adapter adapter : this.sections.values())
				total += adapter.getCount() + 1;
			return total;
		}

		public int getViewTypeCount() {
			// assume that headers count as one, then total all sections
			int total = 1;
			for (Adapter adapter : this.sections.values())
				total += adapter.getViewTypeCount();
			return total;
		}

		public int getItemViewType(int position) {
			int type = 1;
			for (Object section : this.sections.keySet()) {
				Adapter adapter = sections.get(section);
				int size = adapter.getCount() + 1;

				// check if position inside this section
				if (position == 0)
					return TYPE_SECTION_HEADER;
				if (position < size)
					return type + adapter.getItemViewType(position - 1);

				// otherwise jump into next section
				position -= size;
				type += adapter.getViewTypeCount();
			}
			return -1;
		}

		public boolean areAllItemsSelectable() {
			return false;
		}

		public boolean isEnabled(int position) {
			return (getItemViewType(position) != TYPE_SECTION_HEADER);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			int sectionnum = 0;
			for (Object section : this.sections.keySet()) {
				Adapter adapter = sections.get(section);
				int size = adapter.getCount() + 1;

				// check if position inside this section
				if (position == 0)
					return headers.getView(sectionnum, convertView, parent);
				if (position < size)
					return adapter.getView(position - 1, convertView, parent);

				// otherwise jump into next section
				position -= size;
				sectionnum++;
			}
			return null;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

	}
}
